package org.lboot.core.auth.aspect;

import cn.hutool.core.lang.Validator;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.lboot.core.auth.AuthService;
import org.lboot.core.auth.anno.CheckPerm;
import org.lboot.core.domain.ErrMsg;
import org.lboot.core.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author kindear
 * 权限验证切面
 */
@Slf4j
@Aspect
@Component
public class CheckPermAspect {

    @Autowired
    AuthService authService;
    /**
     * 以自定义注解作为切入
     */
    @Pointcut("@annotation(org.lboot.core.auth.anno.CheckPerm)")
    public void CheckPerm(){}

    @Before("CheckPerm()")
    public void doBefore(JoinPoint joinPoint) {
        // 判断是否登录
        if (!authService.isLogin()){
            throw new BusinessException(HttpStatus.UNAUTHORIZED, ErrMsg.build("未登录"));
        }
        // 获取注解
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        // 获取自定义注解信息
        CheckPerm checkPerm = method.getAnnotation(CheckPerm.class);
        // 获取所需权限标识
        String perm = checkPerm.value();
        // 设置为不可访问
        boolean access = false;
        if (Validator.isEmpty(perm)){
            access = true;
        }
        // 非空进行校验
        if (Validator.isNotEmpty(perm)){
            if (authService.hasPerm(perm)){
                access = true;
            }
        }
        String roleKey = checkPerm.orRole();
        // 如果还不能访问，继续校验角色
        if (!access && authService.hasRoleKey(roleKey)){
            access = true;
        }
        if (!access){
            throw new BusinessException(HttpStatus.FORBIDDEN,ErrMsg.build("无权限"));
        }
    }
}
